package com.zhao.dota.security.handler;

import com.zhao.dota.bo.AuthenticateUser;
import com.zhao.dota.security.store.TokenStore;
import com.zhao.dota.security.token.AccessToken;
import com.zhao.dota.security.token.InternalAccessToken;
import com.zhao.dota.struct.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class LoginSuccessHandler extends LoginHandler implements AuthenticationSuccessHandler {

    @Resource
    private TokenStore tokenStore;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        Result<AccessToken> success = Result.success();
        AccessToken accessToken = new InternalAccessToken();
        tokenStore.storeAccessToken(accessToken, (AuthenticateUser) authentication.getPrincipal());
        try {
            success.setData(accessToken);
        } catch (Exception e){
            log.error("登录成功后获取principal失败", e);
        }
        writeResult(response, success, null);
    }
}
